<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item style="font-size: 18px"><i class="el-icon-lx-people"></i>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <!-- 上方按钮 -->
                <el-input v-model="query.UserName" placeholder="用户名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="" icon="el-icon-edit" @click="OpenRole">为用户添加角色</el-button>
                <el-button type="" icon="el-icon-plus" @click="addusers">添加新用户</el-button>
                <el-button type="danger" icon="el-icon-delete" class="handle-del mr10" disabled @click="delAllSelection">批量删除</el-button>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header" @selection-change="handleSelectionChange">
                <!-- 全选框 -->
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <!-- 用户名 -->
                <el-table-column prop="userName" label="用户名" width="100" align="center">
                </el-table-column>
                <!-- 手机号 -->
                <el-table-column prop="userPhone" label="手机号" width="130" align="center">
                </el-table-column>
                <!-- 邮箱地址 -->
                <el-table-column label="头像(查看大图)" width="130" align="center">
                    <template slot-scope="scope">
                        <el-image class="table-td-thumb" :src="scope.row.headPortrait" :preview-src-list="[scope.row.thumb]"></el-image>
                    </template>
                </el-table-column>
                <!-- 邮箱地址 -->
                <el-table-column prop="userMailbox" label="邮箱地址" width="178" align="center">
                </el-table-column>
                <!-- 状态 -->
                <el-table-column label="状态" width="70" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.state == 0">启用</span>
                        <span v-if="scope.row.state == 1">禁用</span>
                    </template>
                </el-table-column>
                <!-- 用户角色 -->
                <el-table-column label="用户角色" width="210" align="center">
                    <template scope="scope">
                        <template v-if="scope.row.roles != null">
                            <el-tag size="small" v-for="item in scope.row.roles" :key="item">{{ item }}</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <!-- 注册时间 -->
                <el-table-column prop="createTime" width="210" label="注册时间" align="center">
                </el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作" width="130" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-delete" class="red" disabled @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next"
                :current-page="query.pageIndex" :page-size="query.pageSize"
                :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>
        <!-- 添加用户 -->
        <el-dialog title="添加用户" :visible.sync="AddVisible" width="50%">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <!-- 用户名称 -->
                <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="ruleForm.userName"></el-input>
                </el-form-item>
                <!-- 用户密码 -->
                <el-form-item label="用户密码" prop="userPassword">
                    <el-input placeholder="请输入密码" v-model="ruleForm.userPassword" show-password></el-input>
                </el-form-item>
                <!-- 手机号 -->
                <el-form-item label="手机号" prop="userPhone">
                    <el-input v-model="ruleForm.userPhone"></el-input>
                </el-form-item>
                <!-- 邮箱 -->
                <el-form-item label="邮箱" prop="userMailbox">
                    <el-input v-model="ruleForm.userMailbox"></el-input>
                </el-form-item>
                <!-- 性别 -->
                <el-form-item label="性别" prop="userSex">
                    <el-radio v-model="ruleForm.userSex" label="男">男</el-radio>
                    <el-radio v-model="ruleForm.userSex" label="女">女</el-radio>
                </el-form-item>
                <!-- 年龄 -->
                <el-form-item label="年龄" prop="userAge">
                    <el-input v-model="ruleForm.userAge"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="AddVisible = false">取 消</el-button>
                <el-button type="primary" @click="add()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 用户添加角色 -->
        <el-dialog title="用户添加角色" v-if="rolequeryVisible" :visible.sync="rolequeryVisible" width="50%">
            <div>
                <el-table ref="multipleTable" :data="roleData" tooltip-effect="dark" style="width: 100%" @selection-change="RolehandleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <!-- 角色名称 -->
                    <el-table-column prop="rName" label="角色名称">
                    </el-table-column>
                    <!-- 角色描述 -->
                    <el-table-column prop="rText" label="角色描述">
                    </el-table-column>
                    <!-- 状态 -->
                    <el-table-column prop="status" label="状态">
                        <template slot-scope="scope">
                            <el-tag :type="scope.row.Status == 1 ? 'danger' : scope.row.status == 0 ? 'success' : ''">
                                {{scope.row.status ? '启用' : '禁用'}}
                            </el-tag>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 确认或取消 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="rolequeryVisible = false">取消</el-button>
                    <el-button type="primary" @click="AddRole">添加</el-button>
                </span>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { deleteUser, updateUser, getUserList, addUser, getUser, rolesUser } from '../../api/user.js';
import { rolelist } from '../../api/role.js';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                UserName: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            roleData: [],
            multipleSelection: [],
            RoleMultipleSelection: [],
            delList: [],
            //添加用户
            AddVisible: false,
            //用户添加角色
            rolequeryVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            ruleForm: {
                userName: '',
                userPassword: '',
                userPhone: '',
                headPortrait: '',
                userMailbox: '',
                userSex: '',
                userAge: undefined,
                createTime: new Date()
            },
            rules: {
                userPhone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
                        message: '手机号格式不正确',
                        trigger: 'blur'
                    }
                ],
                userPassword: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { patterm: /^(?=.* [a-z])(?=.* [A-Z])(?=.*d) [S] {6,16}/, message: '密码格式不正确', trigger: 'blur' }
                ],
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字', trigger: 'blur' }
                ],
                userSex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
                userMailbox: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        pattern:
                            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                        message: '邮箱格式不正确',
                        trigger: 'blur'
                    }
                ],
                userAge: [{ required: true, message: '请输入年龄', trigger: 'blur' }]
            }
        };
    },
    created() {
        this.getData();
    },
    methods: {
        //角色多选操作
        RolehandleSelectionChange(val) {
            this.RoleMultipleSelection = val;
            console.log('下标', this.RoleMultipleSelection);
        },
        AddRole() {
            //定义数组存储角色编号 1,2
            let rId = [];
            this.RoleMultipleSelection.forEach((x) => {
                rId.push(x.rId);
                console.log(rId);
            });
            //定义变量存储用户编号
            var id = '';
            this.multipleSelection.forEach((x) => {
                id = x.id;
                console.log(id);
            });
            let RoleAdd = {
                userId: id,
                roleId: rId.toString()
            };
            console.log('用户角色添加集合', RoleAdd);
            //添加用户角色
            rolesUser(RoleAdd).then((res) => {
                if (res.count == 1) {
                    this.$message.success('用户添加角色成功');
                    this.rolequeryVisible = false;
                    this.getData();
                }
            });
        },
        //角色弹出框
        OpenRole() {
            //判断是否选择用户
            if (this.multipleSelection.length == 0) {
                this.$message.error('请选择用户');
                this.$message.error('请选择用户');
                return;
            } else {
                //选择用户，打开用户弹出框
                this.rolequeryVisible = true;
                rolelist().then((res) => {
                    this.roleData = res.data;
                });
            }
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            getUserList(this.query).then((res) => {
                console.log(res);
                this.tableData = res.data;
                this.pageTotal = res.Count || 50;
            });
            rolesUser().then((res) => {
                console.log(res);
                this.tableData = res.data;
                this.pageTotal = res.Count || 50;
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            });
            deleteUser(row.id).then((res) =>
            {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('删除成功');
                    this.getData();
                } else {
                    this.$message.success(res.Message);
                }
            }).catch(() => {});
        },
        //多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log('用户id', this.multipleSelection);
        },
        //批量删除
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        //分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        //添加触发按钮
        addusers() {
            this.AddVisible = true;
        },
        //用户添加
        add() {
            addUser(this.ruleForm).then((res) => {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('添加成功');
                    this.AddVisible = false;
                    this.getData();
                } else {
                    this.$message.success(res.Message);
                }
            });
        },
        //修改状态
        stateUpdate(index, row) {
            let data = {
                id: row.id,
                userName: row.userName,
                userPassword: row.userPassword,
                userPhone: row.userPhone,
                headPortrait: row.headPortrait,
                userMailbox: row.userMailbox,
                userSex: row.userSex,
                userAge: row.userAge,
                createTime: new Date()
            };
            updateUser(data).then((res) => {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('修改成功');
                    this.AddVisible = false;
                    this.getData();
                } else {
                    this.$message.success(res.Message);
                }
            });
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
